import 'package:flutter/material.dart';
import '../demo/ui_demo.dart';
import 'dart:async';
import 'package:webview_flutter/webview_flutter.dart';
import 'ui_demo26_2.dart';
///https://www.jianshu.com/p/2c721bf5f6e1
class MyDemo extends StatelessWidget implements Demo {
  MyDemo(this.title);
  @override
  final String title;
  @override
  Widget build(BuildContext context) {
    return new HomePage(
      title: this.title,
    );
  }
}

class HomePage extends StatefulWidget {
  final String title;
  HomePage({this.title});
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  int _defaultIndex = 0;
  List<Widget> tabViews;
  List<BottomNavigationBarItem> items = [
    BottomNavigationBarItem(icon: Icon(Icons.search), title: Text("baidu")),
    BottomNavigationBarItem(icon: Icon(Icons.find_in_page), title: Text("so")),
  ];
  Completer<WebViewController>  _completer=new Completer<WebViewController>();
  WebView view1;
  WebView view2;
  WebViewController _webViewController1;
  WebViewController _webViewController2;
  WebViewController _viewController;
  bool so;
  bool baidu;
  List<Widget> views;
  _onTapItem(index) {
    setState(() {
      _defaultIndex = index;
      if (index == 0) {
        _viewController=_webViewController2;
        baidu = false;
        so = true;
      }
      if (index == 1) {
        _viewController=_webViewController1;
        baidu = true;
        so = false;
      }
    });
  }
  _onRefresh(){
    _viewController.reload();
  }
  _onBack(){
   _viewController.canGoBack().then((value){
      if(value) _viewController.goBack();
   });

  }
  _onForward(){
    _viewController.canGoForward().then((value){
      if(value) _viewController.goForward();
    });
  }
  @override
  void initState() {
    super.initState();
    baidu = false;
    so = false;
    view1=WebView(
      key:GlobalKey(),
      initialUrl: "http://106.12.180.103/flutter01.html",
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController webViewController) {
        _webViewController1=webViewController;
        _completer.complete(webViewController);
      },
      javascriptChannels: <JavascriptChannel>[
        _alertJavascriptChannel(context),
        _UserStateJavascriptChannel(context),
      ].toSet(),
      navigationDelegate: (NavigationRequest request) {
        if (request.url.startsWith('js://webview')) {
          print(request.url);
          _webViewController1
              ?.evaluateJavascript('callJS("I am flutter")')
              ?.then((result) {
                  print("result:$result");
          });
          return NavigationDecision.prevent;
        }
        print('allowing navigation to $request');
        return NavigationDecision.navigate;
      },
      onPageFinished: (String url) {
        print('Page finished loading: $url');
      },
    );
    view2=WebView(
      key:GlobalKey(),
      initialUrl: "https://www.baidu.com",
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController webViewController) {
         _webViewController2=webViewController;
      },
      javascriptChannels: <JavascriptChannel>[
        _alertJavascriptChannel(context),
        _UserStateJavascriptChannel(context),
      ].toSet(),
      navigationDelegate: (NavigationRequest request) {
        if (request.url.startsWith('https://www.youtube.com/')) {
          print('blocking navigation to $request}');
          return NavigationDecision.prevent;
        }
        print('allowing navigation to $request');
        return NavigationDecision.navigate;
      },
      onPageFinished: (String url) {
        print('Page finished loading: $url');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            actions: <Widget>[
              IconButton(icon: Icon(Icons.refresh), onPressed: _onRefresh),
              IconButton(icon: Icon(Icons.arrow_back_ios), onPressed: _onBack),
              IconButton(icon: Icon(Icons.arrow_forward_ios), onPressed: _onForward),
              SampleMenus(_completer.future),
              IconButton(icon:Icon(Icons.play_arrow),onPressed: (){
                Navigator.push(context, MaterialPageRoute(builder: (context)=>IndexPage()));
              },),
            ],
          ),
          body: Stack(
            children: [
              Offstage(
                  offstage: so,
                  child: SafeArea(child: Container(
                    width: double.infinity,
                    height: double.infinity,
                    child: view1,
                  ))
              ),
              Offstage(
                  offstage: baidu,
                  child:SafeArea(child: Container(
                    width: double.infinity,
                    height: double.infinity,
                    child: view2,
                  ))
              ),
            ],
          ),
          bottomNavigationBar: BottomNavigationBar(
            type:BottomNavigationBarType.fixed ,
            currentIndex: _defaultIndex,
            items: items,
            onTap: _onTapItem,
          ),
        ));
  }
  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toast',
        onMessageReceived: (JavascriptMessage message) {
          Scaffold.of(context).showSnackBar(SnackBar(
            content: Text(message.message),
          ));
        });
  }
  JavascriptChannel _UserStateJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'UserState',
        onMessageReceived: (JavascriptMessage message) {
          Scaffold.of(context).showSnackBar(SnackBar(
            content: Text(message.message),
          ));
        });
  }

  @override
  void dispose() {
    super.dispose();
  }
}

class SampleMenus extends StatelessWidget {
  final Future<WebViewController> future;
  SampleMenus(this.future);
  _onSelected(WebViewController _webViewController,BuildContext context,String value) async{
    if("cookies"==value){
      final String cookies =
          await _webViewController.evaluateJavascript('document.cookie');
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const Text('Cookies:'),
            _getCookieList(cookies),
          ],
        ),
      ));
    }
  }
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: future,
      builder: (BuildContext context, AsyncSnapshot<WebViewController> webViewController){
        return PopupMenuButton(
            onSelected: (value){
              _onSelected(webViewController.data, context, value);
            },
            itemBuilder: (BuildContext context)=>[
          PopupMenuItem(value:"cookies",child: Text("show cookies")),
          PopupMenuItem(value:"agent",child: Text("show agent"))
        ]);
      },
    );
  }
  Widget _getCookieList(String cookies) {
    if (cookies == null || cookies == '""') {
      return Container();
    }
    final List<String> cookieList = cookies.split(';');
    final Iterable<Text> cookieWidgets =
    cookieList.map((String cookie) => Text(cookie));
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      mainAxisSize: MainAxisSize.min,
      children: cookieWidgets.toList(),
    );
  }
}
